<template>
  <div>
    <!--面包屑区域-->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="10">
        <!--搜索框-->
        <el-col :span="12">
          <el-input
              placeholder="输入查找用户"
              prefix-icon="el-icon-search"
              v-model="queryInfo.query"
              clearable
              @keyup.enter.native="getUsersList(queryInfo['pagenum'] = 1)">
          </el-input>
        </el-col>
        <!--添加按钮-->
        <el-col :span="6" :offset="1">
          <el-button type="primary" plain @click="addDialogVisible = true"><i class="el-icon-plus"></i> 添加用户
          </el-button>
        </el-col>
      </el-row>
      <!--表格区域-->
      <el-table
          :data="userList"
          border
          style="width: 100%">
        <el-table-column prop="username" type="index"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="100px" v-slot="scope">
          <template>
            <!--滑块功能-->
            <el-switch
                v-model="scope.row.mg_state"
                active-color="#F7CE4A"
                inactive-color="#FFE8B6"
                @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250px">
          <template v-slot="scope">
            <el-link icon="el-icon-edit" :underline="false" @click="abc(scope.row)">编辑</el-link>
            <el-link icon="el-icon-delete" type="danger" :underline="false">删除</el-link>
            <el-link icon="el-icon-setting" type="warning" :underline="false">分配角色</el-link>
          </template>
        </el-table-column>
      </el-table>
      <!--分页效果区域-->
      <el-pagination
          background
          layout="total, prev, pager, next"
          :page-size=4
          :total="total"
          @current-change="handleCurChange">
      </el-pagination>
      
      <!--添加用户对话框-->
      <el-dialog title="设置基本信息" :visible.sync="addDialogVisible" @close="addDialogClose">
        <el-form :model="addUserForm" :rules="addRules" stateicon status-icon ref="ruleForm">
          <el-form-item label="用户名:" label-width="100px" prop="user">
            <el-input v-model="addUserForm.user"></el-input>
          </el-form-item>
          <el-form-item label="密码:" label-width="100px" prop="password">
            <el-input v-model="addUserForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" label-width="100px" prop="checkPass">
            <el-input v-model="addUserForm.checkPass" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" label-width="100px" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号:" label-width="100px" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click.native="addUser">确 定</el-button>
        </div>
      </el-dialog>
    
    </el-card>
  </div>

</template>

<script>
  import {getUsers, putUserState, postUser} from "network/users";

  export default {
    name: "Users",
    data() {
      var validatePass = (rule, value, cb) => {
        //验证两次密码一致性
        if (value !== this.addUserForm.password) {
          cb(new Error('两次输入密码不一致!'));
        } else {
          cb();
        }
      };
      var validatorEmail = (rule, value, cb) => {
        //验证邮箱的正则
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          //合法邮箱
          cb()
        } else {
          cb(new Error('请输入合法的邮箱!'))
        }
      };
      var validatorMobile = (rule, value, cb) => {
        //验证邮箱的正则
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (regMobile.test(value)) {
          //合法手机号码
          cb()
        } else {
          cb(new Error('请输入合法的手机号码!'))
        }
      }
      return {
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 4
        },
        userList: [],
        total: 0,
        dialogFormVisible: false,
        addUserForm: {
          user: '',
          password: '',
          email: '',
          mobile: ''
        },
        addDialogVisible: false,
        addRules: {
          user: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 3, max: 10, message: '长度必须在 3 到 10 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
          ],
          checkPass: [
            {required: true, message: '请再次输入密码', trigger: 'blur'},
            {validator: validatePass, trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: validatorEmail, trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {validator: validatorMobile, trigger: 'blur'}
          ]
        }


      }
    },
    created() {
      this.getUsersList()
    }
    ,
    methods: {
      async getUsersList() {
        const {data: res} = await getUsers(this.queryInfo)
        if (res.meta.status !== 200) return this.$message.error('请求用户数据失败，请联系管理员')
        this.userList = res.data.users
        this.total = res.data.total
      }
      ,
      //监听页码发生改变
      handleCurChange(page) {
        this.queryInfo.pagenum = page
        this.getUsersList()
      }
      ,
      //监听 switch 开关状态改变
      async userStateChange(userinfo) {
        const {data: res} = await putUserState(userinfo.id, userinfo.mg_state)
        if (res.meta.status !== 200) {
          userinfo.mg_state = !userinfo.mg_state
          return this.$message.error('状态修改失败，请联系管理员!')
        }
        this.$message.closeAll()
        this.$message.success('状态修改成功~')
      },
      //监听添加用户对话框的关闭
      addDialogClose() {
        this.$refs.ruleForm.resetFields()
      },
      //监听添加用户对话框的确定按钮
      addUser() {
        this.$refs.ruleForm.validate(async valid => {
          if (!valid) return
          /*发送post请求*/
          delete this.addUserForm.checkPass
          console.log(this.addUserForm);
          const {data: res} = await postUser(this.addUserForm)
          console.log(res);
          if (res.meta.status !== 201) return this.$message.error('这个功能暂时用不了，后台技术不行，数据传不过来！')
          this.$message.success('添加用户成功！')
          //关闭对话框
          this.addDialogVisible = false
          this.getUsersList()
        })
      },
      abc(obj) {
        console.log(obj);
      }
    }
  }
</script>

<style lang="less" scoped>
  /deep/ .el-table {
    .cell {
      display: flex;
      justify-content: space-around;
    }
    
    .el-link--inner {
      margin-left: 0;
    }
    
  }
</style>